<template>
  <a-modal
    title="编辑违章隐患标准"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-spin :spinning="formLoading">
      <a-form :form="form" >
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item
              label="文档类别"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-select allow-clear placeholder="请选择文档类别" v-model="submitInfo.standardCode" required @change="typeChanged">
                <a-select-option v-for="(item) in havStandardData" :key="item.id" :value="item.code">{{ item.item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-item
              label="文档名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input v-model="submitInfo.fileName" placeholder="显示文档名称" :disabled="true"/>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-item
              style="width: 100%"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="上传文档"
            >
              <a-upload
                name="fileCode"
                :before-upload="beforeUpload"
                @change="handleFileChange"
                :disabled="uploadedFile !== null"
                :defaultFileList="defaultFileList"
              >
                <a-button>
                  <a-icon type="upload" /> 点击上传文档
                </a-button>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import IconSelector from '@/components/IconSelector'
  import {
    editQHSEHavStandard,
    getQHSEHavStandardList
  } from '../../../api/modular/system/QHSEHavStandard'
  export default {
    components: { IconSelector },

    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        formLoading: false,
        params: {},
        queryParam: {},
        havStandardData: [],
        headers: {
          authorization: 'authorization-text'
        },
        fileCode: '',
        submitInfo: {
          id: '',
          standardCode: '',
          fileName: '',
          file: {
            name: '',
            base64Content: ''
          }
        },
        uploadedFile: null,
        visibleIcon: false,
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        isPDF: true,
        defaultFileList: [
          {
            uid: '1',
            name: ''
          }
        ],
        isChanged: false
      }
    },
    created() {
      this.getQHSEHavStandardTree()
    },
    methods: {
      // 变化了，则将是否改变的状态变成true
      typeChanged() {
        this.isChanged = true
      },
      // 上传文件前，控制只能传pdf文件
      beforeUpload(file) {
        const isPDF = file.type === 'application/pdf'
        if (!isPDF) {
          this.$message.error('只能上传 PDF 文件！')
          this.isPDF = false
          this.uploadedFile = null // 重置已上传的文件信息
        }
        return false
      },
      // 上传文件
      handleFileChange(info) {
        console.log('fileInfo', info.file)
        if (info.file.status !== 'removed') {
          const isPDF = info.file.type === 'application/pdf'
          if (isPDF) {
          this.uploadError = true // 重置上传错误状态
          this.isChanged = true
          this.uploadedFile = info.file.response // 保存已上传的文件信息
          this.submitInfo.file.name = info.file.name.split('.')[0]
          this.submitInfo.fileName = info.file.name.split('.')[0]
          // this.defaultFileList = null
          console.log('fileName', this.submitInfo.file.name)
          const file = info.file
          // if (file.status === 'done') {
          const reader = new FileReader()
          reader.onload = (e) => {
            // 将文件内容读取为 Base64 格式
            const base64String = e.target.result
            this.fileCode = base64String.split(',')[1]
            this.submitInfo.file.base64Content = this.fileCode
            console.log('submitInfo', this.submitInfo)
          }
          reader.readAsDataURL(file)
          } else {
            // this.visible = true // 文件不是PDF，隐藏组件
            this.uploadedFile = null // 重置已上传的文件信息
            this.submitInfo = { // 清空相关的数据
              standardCode: '',
              fileName: '',
              file: {
                name: '',
                base64Content: ''
              }
            }
            this.isPDF = false
            // this.reloadComponentKey = !this.reloadComponentKey
          }
        }
      },
      handleChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList)
        }
        if (info.file.status === 'done') {
          this.$message.success(`${info.file.name} file uploaded successfully`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} file upload failed.`)
        }
      },
      // 获取文档类别列表
      getQHSEHavStandardTree() {
        getQHSEHavStandardList(Object.assign(this.params)).then(res => {
          this.treeLoading = false
          if (!res.success) {
            return
          }
          this.havStandardData = res.data
        })
      },
      // 打开页面初始化
      edit (record) {
        console.log('record', record)
        const standardItem = record.standardCode
        const searchResult = this.havStandardData.find(obj => obj.item === standardItem)
        console.log('searchResult', searchResult)
        this.submitInfo.standardCode = searchResult.code
        this.submitInfo.fileName = record.fileName
        this.submitInfo.id = record.id
        this.submitInfo.file.name = record.file.name
        this.submitInfo.file.base64Content = record.file.base64Content
        this.defaultFileList[0].name = record.fileName + '.pdf'
        this.visible = true
        this.form.getFieldDecorator('visible', { initialValue: true })
        this.formLoading = false
        console.log('初始的submitInfo', this.submitInfo)
      },
      // 实现编辑文档
      handleSubmit () {
        if (this.isChanged === true) {
          console.log('submitInfoEdit', this.submitInfo)
          if (this.submitInfo.standardCode === '') {
            this.$message.warning('请选择文档类别！')
          }
          if (this.submitInfo.fileName === '') {
            this.$message.warning('请上传文档！')
          }
          if (this.submitInfo.standardCode !== '' && this.submitInfo.fileName !== '') {
            editQHSEHavStandard(this.submitInfo).then(response => {
              this.$message.success('编辑文档成功！')
              // 重置表单内数据
              this.submitInfo.standardCode = ''
              // this.defaultFileList = null
              this.uploadedFile = null
              this.form.resetFields()
              this.confirmLoading = false
              this.visible = false
              this.isChanged = false
            })
              .catch(error => {
                // 处理错误
                console.error(error)
                // 处理上传失败后的逻辑
                this.$message.error('编辑文档失败！')
              })
          }
        } else {
          this.handleCancel()
        }
      },
      handleCancel () {
        // 重置表单内数据
        this.isChanged = false
        this.submitInfo.standardCode = ''
        this.uploadedFile = null
        this.form.resetFields()
        this.confirmLoading = false
        this.visible = false
      }
    }

  }
</script>
